import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:test1/View/MyRowText.dart';

class Flutter_Data_File_Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return Flutter_Data_File_State();
  }

}

class Flutter_Data_File_State extends State<Flutter_Data_File_Page> {
  String result = "";

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("文件本地存储与读取"),
        ),
        body: ListView(
          children: <Widget>[
            MyRowText("存储到本地", () async {
              String str = await writeToLocal("abcdef") as String;
              setState(() {
                result = str;
              });
            }),
            MyRowText("从本地读取", () async {
              String str = await readFromLocal() as String;
              setState(() {
                result = str;
              });
            }),
            Container(
              margin: EdgeInsets.all(50.0),
              child: Text(result),
            ),
          ],
        ),
      ),
    );
  }

  Future<String> writeToLocal(String data) async {
    String tempDir = (await getTemporaryDirectory()).path;
    File file = await File("$tempDir/test.txt");
    File result = await file.writeAsString(data);
    print(result.path);
    if (result.existsSync()) {
      return "保存成功，数据为：$data ,  存储路径为$result";
    } else {
      return "保存失败";
    }
  }

  Future<String> readFromLocal() async {
    String tempDir = (await getTemporaryDirectory()).path;
    File file = await File("$tempDir/test.txt");
    String result = await file.readAsString();
    if (result != null) {
      return "读取成功，读取结果为：$result";
    } else {
      return "读取失败";
    }
  }
}
